package com.diy.sigmund.diyuser.service.impl;

import com.diy.sigmund.diycommon.entity.ResultMsg;
import com.diy.sigmund.diycommon.entity.base.exception.DiyRuntimeException;
import com.diy.sigmund.diycommon.entity.enumerate.ResponseEnum;
import com.diy.sigmund.diycommon.util.time.DateUtil;
import com.diy.sigmund.diyuser.feign.client.SeataOrderClient;
import com.diy.sigmund.diyuser.mapper.TestSqlMapper;
import com.diy.sigmund.diyuser.service.SeataUserService;
import java.math.BigDecimal;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author ylm-sigmund
 * @since 2022/11/12 17:00
 */
@Service
public class SeataUserServiceImpl implements SeataUserService {

    @Autowired
    private TestSqlMapper testSqlMapper;
    @Autowired
    private SeataOrderClient seataOrderClient;
    private static final Logger log = LoggerFactory.getLogger(SeataUserServiceImpl.class);

    @Override
    public ResultMsg decreaseInventory(String commodityId, Integer transactionQuantity) {
        log.info("------->扣减库存开始");
        ResultMsg resultMsg = seataOrderClient.decreaseInventory(commodityId, transactionQuantity);
        log.info("------->扣减库存结束:{}", resultMsg);
        return ResultMsg.success("Decrease stock success");
    }

    @Override
    public ResultMsg decreaseAccount(String orderId, BigDecimal transactionAmount) {
        log.info("------->扣减账户开始account中");
        testSqlMapper.decreaseAccount(transactionAmount);
        log.info("------->扣减账户结束account中");

        //修改订单状态，此调用会导致调用成环
        log.info("修改订单状态开始");
        ResultMsg mes = seataOrderClient.update(orderId, "0");
        log.info("修改订单状态结束：{}", mes);
        // if (new Date().after(DateUtil.parseStrToDate("2018", DateUtil.DATE_FORMAT_YYYY))) {
        //     throw new DiyRuntimeException(ResponseEnum.INTERNAL_SERVER_BUSY);
        // }
        //模拟超时异常，全局事务回滚
        try {
            Thread.sleep(30 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return ResultMsg.success("Account decrease success");
    }
}
